package com.song.user.config.mybatis;

import com.song.common.annotation.SensitiveData;
import com.song.common.util.SensitiveUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.sql.Statement;
import java.util.List;
import java.util.Properties;

/**
 * mybatis 对查询结果中需要解密的数据解密
 */
@Slf4j
@Component
@Intercepts({
        @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})
})
public class DecryptInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        if (result != null){
            if (result instanceof List){
                List list = (List) result;
                if (!CollectionUtils.isEmpty(list) && needDecrypt(list.get(0))){
                    for (Object obj : list) {
                        SensitiveUtil.decrypt(obj);
                    }
                }
            }else {
                SensitiveUtil.decrypt(result);
            }
        }
        return result;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    public boolean needDecrypt(Object object){
        Class<?> objectClass = object.getClass();
        SensitiveData sensitiveData = AnnotationUtils.findAnnotation(objectClass, SensitiveData.class);
        return ObjectUtils.isNotEmpty(sensitiveData);
    }
}
